package crawler.web.berkeleydb;

import java.io.File;

import library.database.mongo.ObjectId;

import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.StoreConfig;

import crawler.web.beans.PageFingerPrint;

public class SimpleStorePut {
	//Finally, to complete our class, we need a main() method, which simply calls our run() method.
	// main
	public static void main(String args[]) {
		SimpleStorePut ssp = new SimpleStorePut();
		try {
			ssp.run();
		} catch (DatabaseException dbe) {
			System.err.println("SimpleStorePut: " + dbe.toString());
			dbe.printStackTrace();
		} catch (Exception e) {
			System.out.println("Exception: " + e.toString());
			e.printStackTrace();
		}
		System.out.println("All done.");
	}

	private static File envHome = new File("source/crawler/berkeleydb/3");
	private Environment envmnt;
	private EntityStore store;
	private SimpleDA sda;

	//Next we create a method that simply opens our database environment and entity store for us.
	// The setup() method opens the environment and store
	// for us.
	public void setup() throws DatabaseException {

		EnvironmentConfig envConfig = new EnvironmentConfig();
		StoreConfig storeConfig = new StoreConfig();

		envConfig.setAllowCreate(true);
		storeConfig.setAllowCreate(true);

		envHome.mkdirs();
		// Open the environment and entity store
		envmnt = new Environment(envHome, envConfig);
		store = new EntityStore(envmnt, "EntityStore", storeConfig);
	}

	//We also need a method to close our environment and store.
	// Close our environment and store.
	public void shutdown() throws DatabaseException {

		store.close();
		envmnt.close();
	}

	//Now we need to create a method to actually write objects to our store. This method creates a SimpleDA object (see SimpleDA.class that we will use to access our indexes. Then we instantiate a series of CrawlURL (see A Simple Entity Class) objects that we will place in our store. Finally, we use our primary index (obtained from the SimpleDA class instance) to actually place these objects in our store.
	//In Retrieving Objects from an Entity Store we show a class that is used to retrieve these objects.
	// Populate the entity store
	private void run() throws DatabaseException {

		setup();

		// Open the data accessor. This is used to store
		// persistent objects.
		sda = new SimpleDA(store);

		// Instantiate and store some entity classes
		PageFingerPrint sec1 = new PageFingerPrint();
		sec1.set_id(new ObjectId("123"));
		sec1.setFingerPrint(33242L);
		sda.pIdx.put(sec1);
		sec1.set_id(new ObjectId("123s"));
		sec1.setFingerPrint(33242L);
		sda.pIdx.put(sec1);
		sec1.set_id(new ObjectId("12ss3s"));
		sec1.setFingerPrint(332422L);
		sda.pIdx.put(sec1);

		shutdown();
	}

}